import React, {FC, useCallback, useEffect, useMemo, useState} from 'react';
import {createFromIconfontCN} from "@ant-design/icons";
import "./css/GlobalIcon.less";
import { getIconUrl } from '../services/FileService';
const FontIcon = createFromIconfontCN({
    // 请给新图标一个合适的驼峰命名，并保证单词正确
    scriptUrl: window.location.origin + "/iconFont.js?_=" + Math.random(),
});

const FontImg = (props: any) => {
    return <img {...props} src={getIconUrl(props.iconId)} width={props.size} height={props.size}/>
}

interface GlobalIconProps {
    style?: object,
    size?: number,
    name: string,
    className?: string
    onClick?: Function
}

const GlobalIcon: FC<GlobalIconProps> = (props) => {

    const [icon, setIcon] = useState<any>({
        com: FontIcon,
        comProps: {
            name: "iocn-shezhi1",
            style: {fontSize: 16},
            className: "iconfont sfFontFamily"
        }
    });

    const initIcon = useCallback(async () => {
        const {name = "", size = 16}: { name: string, size: 16 } = props;
        let component = FontIcon, comProps: any = {};
        if (!name || name.indexOf("icon") !== -1) {
            component = FontIcon;
            comProps = {
                type: name || "iocn-shezhi1",
                style: {fontSize: size},
                className: "iconfont sfFontFamily"
            }
        } else {
            component = FontImg;
            comProps = {
                size: size,
                iconId: name
            }
        }
        setIcon({
            com: component,
            comProps,
        })
    }, [props.name]);

    useEffect(() => {
        initIcon()
    }, [props.name]);

    const renderGlobalIcon = useMemo(() => {
        const {style = {}}: { style: any } = props;
        let Com = icon.com;
        return (
            <div className={"sf_core_icon " + (props.className || "")} onClick={(event: any) => {
                props.onClick && props.onClick(event)
            }} style={style}>
                <Com {...icon.comProps}/>
            </div>
        )
    }, [icon, props.className]);

    return (renderGlobalIcon);
};

export default React.memo(GlobalIcon);